package com.example.controller;

import com.example.entity.Department;
import com.example.entity.Student;
import com.example.entity.User;
import com.example.entity.bo.StudentCourseResultBO;
import com.example.entity.example.DepartmentExample;
import com.example.entity.example.StudentExample;
import com.example.entity.vo.StudentVO;
import com.example.security.SecurityUser;
import com.example.service.DepartmentService;
import com.example.service.LectureService;
import com.example.service.StudentService;
import com.example.service.UserService;
import com.example.util.CustomConstant;
import com.example.util.CustomUtil;
import com.example.util.ResultEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/student")
@Controller
public class StudentController {
    @Autowired
    UserService userService;

    @Autowired
    StudentService studentService;

    @Autowired
    DepartmentService departmentService;

    @Autowired
    LectureService lectureService;

    public StudentVO transformToStudentVO(Student student) {
        StudentVO studentVO = new StudentVO();
        BeanUtils.copyProperties(student, studentVO);

        Integer departmentId = student.getDepartmentId();
        Department department = departmentService.getById(departmentId);
        if (department != null) {
            studentVO.setDepartmentName(department.getName());
        }
        studentVO.setBoarder(student.getBoarder() ? "是" : "否");

        return studentVO;
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("/get.json")
    public ResultEntity<List<StudentVO>> get(@RequestParam("page") Integer page,
                                             @RequestParam("limit") Integer limit,
                                             @RequestParam(value = "id", required = false) String id,
                                             @RequestParam(value = "name", required = false) String name,
                                             @RequestParam(value = "gender", required = false) String gender,
                                             @RequestParam(value = "politicalStatus", required = false) String politicalStatus
    ) {
        StudentExample example = new StudentExample();
        StudentExample.Criteria criteria = example.createCriteria();
        if (id != null && !id.isEmpty()) {
            id = '%' + id + '%';
            criteria.andIdLike(id);
        }
        if (name != null && !name.isEmpty()) {
            name = '%' + name + '%';
            criteria.andNameLike(name);
        }
        if (politicalStatus != null && !politicalStatus.isEmpty()) {
            criteria.andPoliticalStatusEqualTo(politicalStatus);
        }
        if (gender != null && !gender.isEmpty()) {
            criteria.andGenderEqualTo(gender);
        }
        List<Student> students = studentService.getByExampleWithLimit(example, page, limit);
        List<StudentVO> studentVOs = new ArrayList<>(students.size());
        for (Student student : students) {
            StudentVO studentVO = this.transformToStudentVO(student);
            studentVOs.add(studentVO);
        }
        long count = studentService.getCountByExample(example);
        return ResultEntity.createResultEntity(0, null, count, studentVOs);
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @RequestMapping("/add/page.html")
    public String addPage(ModelMap modelMap) {
        List<Department> deptList = departmentService.getByExampleWithLimit(new DepartmentExample(), 1, Integer.MAX_VALUE);
        modelMap.addAttribute("deptList", deptList);
        return "student/student-add";
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("add")
    public ResultEntity<Object> add(@RequestBody Student student) {
        String id = student.getId();
        if (studentService.getById(id) != null) {
            return ResultEntity.failedWithoutData(CustomConstant.MESSAGE_THE_STUDENT_ID_ALREADY_EXISTS);
        }
        studentService.add(student);
        return ResultEntity.successWithoutData();
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @RequestMapping("/{id}/modify/page.html")
    public String modifyPage(ModelMap modelMap, @PathVariable("id") String id) {
        Student student = studentService.getById(id);
        List<Department> deptList = departmentService.getByExampleWithLimit(new DepartmentExample(), 1, Integer.MAX_VALUE);
        modelMap.addAttribute("student", student);
        modelMap.addAttribute("deptList", deptList);
        return "student/student-modify";
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("/update")
    public ResultEntity<Object> update(@RequestBody Student student) {
        studentService.updateById(student);
        return ResultEntity.successWithoutData();
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("/remove")
    public ResultEntity<Object> remove(@RequestParam("id") String id) {
        studentService.removeById(id);
        return ResultEntity.successWithoutData();
    }


    @RequestMapping("/course/results/page.html")
    public String courseResultsPage(ModelMap modelMap, HttpSession session) {
        SecurityUser securityUser = CustomUtil.getCurrentUser(session);
        String id = securityUser.getOriginalUser().getBindId();
        modelMap.addAttribute("id", id);
        return "student/course-result-list";
    }

    /**
     * @param id 学号
     */
    @PreAuthorize("hasRole('ROLE_管理员')")
    @RequestMapping("/{id}/course/results/page.html")
    public String courseResultsPageWithId(ModelMap modelMap, @PathVariable("id") String id) {
        modelMap.addAttribute("id", id);
        return "student/course-result-list";
    }

    /**
     * 学生成绩
     *
     * @param id 学号
     */
    @ResponseBody
    @RequestMapping("/get/course/results.json")
    public ResultEntity<List<StudentCourseResultBO>> getCourseResults(@RequestParam("id") String id, HttpSession session) {
        User me = CustomUtil.getCurrentUser(session).getOriginalUser();
        if (!"管理员".equals(me.getRole()) && !me.getBindId().equals(id)) {
            // 没有管理员权限不能查看其他学生成绩
            return ResultEntity.failedWithoutData(CustomConstant.MESSAGE_ACCESS_DENIED);
        }

        // 获取该学生的成绩
        List<StudentCourseResultBO> courseResultBOS = studentService.getStudentCourseResultsById(id);
        return ResultEntity.createResultEntity(0, null, (long) courseResultBOS.size(), courseResultBOS);
    }
}
